package cn.mumzone.pos.ui.fragment;

import android.app.Dialog;
import android.content.DialogInterface;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.base.BaseFragment;
import cn.mumzone.basic.dialog.AlertDialog;
import cn.mumzone.basic.loading.button.LoadingButton;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.EditTextUtil;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.NetUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.RxBus;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.pos.R;
import cn.mumzone.pos.dialog.PosAlertDialog;
import cn.mumzone.pos.dialog.PosDialog;
import cn.mumzone.pos.event.MoreViewChangeEvent;
import cn.mumzone.pos.event.StockSearchResultEvent;
import cn.mumzone.pos.model.AddInventoryEntity;
import cn.mumzone.pos.model.GoodsEntity;
import cn.mumzone.pos.model.InventoryDetailEntity;
import cn.mumzone.pos.model.RepoGoodsEntity;
import cn.mumzone.pos.model.RepoListGoodsEntity;
import cn.mumzone.pos.model.RepositoryEntity;
import cn.mumzone.pos.presenter.StockCheckPresenter;
import cn.mumzone.pos.presenter.contract.StockCheckContract;
import cn.mumzone.pos.ui.activity.ACT_SearchStock;
import cn.mumzone.pos.ui.adapter.ADA_InventoryGoods;
import cn.mumzone.pos.ui.adapter.ADA_SelectRepository;
import cn.mumzone.pos.ui.adapter.ADA_StockCheck;

/**
 * Created by JoeLjt on 2019/9/26.
 * Email: lijiateng1219@gmail.com
 * Description:
 */

public class FRA_StockCheck extends BaseFragment<StockCheckPresenter> implements StockCheckContract.View {

    @BindView(R.id.et_scan)
    EditText etScan;

    @BindView(R.id.ll_repository)
    LinearLayout llRepository;
    @BindView(R.id.tv_repository)
    TextView tvRepository;

    @BindView(R.id.ll_empty_cart)
    LinearLayout llDefault;
    @BindView(R.id.rv_cart_goods)
    LRecyclerView rvCart;

    @BindView(R.id.rg_type)
    RadioGroup rgType;

    @BindView(R.id.tv_bill_date)
    TextView tvBillDate;
    @BindView(R.id.tv_clear_selected)
    TextView tvClear;
    @BindView(R.id.tv_add_stock)
    TextView tvAddStock;
    @BindView(R.id.btn_generate)
    LoadingButton btnGenerate;

    private PosAlertDialog deleteConfirmDialog;
    private PosAlertDialog clearConfirmDialog;

    private AlertDialog mScanGoodsDialog;
    private ADA_StockCheck mScanGoodsAdapter;
    private CheckBox cbCheckAll;


    private AlertDialog mSelectRepoDialog;
    private ADA_SelectRepository mRepoAdapter;

    private LRecyclerViewAdapter mGoodsViewAdapter;
    private ADA_StockCheck mStockCartAdapter;

    private boolean isScanExecuted = false;

    private RepositoryEntity mSelectedRepo;


    @Override
    protected void onUserVisible() {
        etScan.requestFocus();
    }

    @Override
    protected void initEventAndData() {

        initViews();

        initSelectRepoDialog();

        initScanGoodsDialog();

        mPresenter.loadRepositoryList();

    }

    private void initViews() {

        updateStockSearchResultUI(true);
        tvBillDate.setText(AppDateUtil.getTimeStamp(System.currentTimeMillis(), AppDateUtil.YYYY_MM_DD));

        rvCart.setLayoutManager(new LinearLayoutManager(mContext));
        mStockCartAdapter = new ADA_StockCheck(mContext, true);
        mStockCartAdapter.setOnItemDeleteClickedListener(new ADA_StockCheck.OnItemDeleteClickedListener() {
            @Override
            public void OnClicked(final int position, RepoListGoodsEntity repoGoodsEntity) {
                showDeleteConfirmDialog(position);
            }
        });
        mGoodsViewAdapter = new LRecyclerViewAdapter(mStockCartAdapter);
        rvCart.setAdapter(mGoodsViewAdapter);
        rvCart.setPullRefreshEnabled(false);
        rvCart.setLoadMoreEnabled(false);

        etScan.setInputType(InputType.TYPE_NULL);
        EditTextUtil.hideSoftInputMethod(mContext, etScan);
        etScan.requestFocus();
        etScan.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                String code = v.getText().toString().trim();
                if (actionId == KeyEvent.ACTION_DOWN && !TextUtils.isEmpty(code)) {

                    if (mSelectedRepo == null || TextUtils.isEmpty(mSelectedRepo.getId())) {
                        PosToast.INSTANCE.makeShortToast(mContext, "请先选择仓库");
                        isScanExecuted = false;
                        return true;
                    }

                    if (!NetUtil.isNetworkAvailable(mContext)) {
                        PosToast.INSTANCE.makeShortToast(mContext, "网络不给力，请稍候再试");
                        return true;
                    }

                    if (!isScanExecuted) {
                        mPresenter.loadRepoGoodsById(mSelectedRepo != null ? StringUtils.get(mSelectedRepo.getId()) : "", code, "4");
                        rvCart.setNoMore(false);
                    }
                    isScanExecuted = true;
                    etScan.setText("");
                }
                return true;
            }
        });

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            mPresenter.loadRepositoryList();
        }
    }

    private void updateStockSearchResultUI(boolean showDefault) {
        llDefault.setVisibility(showDefault ? View.VISIBLE : View.GONE);
        rvCart.setVisibility(!showDefault ? View.VISIBLE : View.GONE);
        btnGenerate.setEnabled(false);
    }

    @Override
    protected int getLayout() {
        return R.layout.fra_check_stock;
    }

    @OnClick({R.id.iv_back, R.id.ll_repository, R.id.tv_clear_selected, R.id.tv_add_stock, R.id.btn_generate})
    void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                RxBus.getDefault().post(new MoreViewChangeEvent(MoreViewChangeEvent.MORE_VIE_HOME));
                break;
            case R.id.ll_repository:
                showDialog(mSelectRepoDialog);
                break;
            case R.id.tv_clear_selected:
                showClearConfirmDialog();
                break;
            case R.id.tv_add_stock:
                if (mSelectedRepo == null) {
                    showError("请先选择仓库");
                    return;
                }
                ACT_SearchStock.startAct(getActivity(), mSelectedRepo, mStockCartAdapter.getDataList());
                break;
            case R.id.btn_generate:
                doGenerateBill();
                break;
        }
    }

    private void showDeleteConfirmDialog(final int position) {
        deleteConfirmDialog = new PosAlertDialog.Builder(mContext)
                .setRemindText("确认要删除商品吗？")
                .setPrimaryText("确认删除")
                .setPrimaryLoadingText("删除中")
                .setUseLoadingButton(true)
                .setOnConfirmClickListener(new PosAlertDialog.OnConfirmClickListener() {
                    @Override
                    public void onConfirmClick(View view, Dialog dialog) {
                        mStockCartAdapter.getDataList().remove(position);
                        mStockCartAdapter.notifyDataSetChanged();
                        deleteConfirmDialog.dismiss();
                        if (ListUtil.isListEmpty(mStockCartAdapter.getDataList())) {
                            updateStockSearchResultUI(true);
                        }
                        PosToast.INSTANCE.makeCheckMarkToast(mContext, "已删除");
                    }
                }).build();
        deleteConfirmDialog.show();
    }

    private void showClearConfirmDialog() {
        clearConfirmDialog = new PosAlertDialog.Builder(mContext)
                .setRemindText("确认要删除所有已选择的商品吗？")
                .setPrimaryText("全部删除")
                .setPrimaryLoadingText("删除中")
                .setUseLoadingButton(true)
                .setOnConfirmClickListener(new PosAlertDialog.OnConfirmClickListener() {
                    @Override
                    public void onConfirmClick(View view, Dialog dialog) {
                        mStockCartAdapter.clear();
                        tvClear.setEnabled(false);
                        btnGenerate.setEnabled(false);
                        updateStockSearchResultUI(true);
                        clearConfirmDialog.dismiss();
                        PosToast.INSTANCE.makeCheckMarkToast(mContext, "已删除");
                    }
                }).build();
        clearConfirmDialog.show();
    }

    private void doGenerateBill() {
        btnGenerate.startLoading("正在生成盘点单");
        String repoId = mSelectedRepo.getId();
        String repoType = getRepoType(((RadioButton) (
                rgType.findViewById(rgType.getCheckedRadioButtonId()))).getText().toString());
        String goodsJson = getGoodJson(mStockCartAdapter.getDataList());
        mPresenter.generateCheckBill(repoId, mSelectedRepo.getRepositoryName(), repoType, goodsJson);
    }

    private String getGoodJson(List<RepoListGoodsEntity> dataList) {
        ArrayList<AddInventoryEntity> arrayList = new ArrayList<>();
        for (RepoListGoodsEntity entity : dataList) {

            if (!ListUtil.isListEmpty(entity.getGoodsBatch())) {
                for (RepoGoodsEntity batchEntity : entity.getGoodsBatch()) {
                    AddInventoryEntity inventoryEntity = new AddInventoryEntity();
                    inventoryEntity.setGoodsName(entity.getGoodsName());
                    inventoryEntity.setGoodsSpec(ListUtil.isListEmpty(entity.getParameter()) ? "" : JSON.toJSONString(entity.getParameter()));
                    inventoryEntity.setGoodsName(batchEntity.getName());
                    inventoryEntity.setGoodsId(batchEntity.getId());
                    inventoryEntity.setGoodsCode(batchEntity.getGoodsCode());
                    inventoryEntity.setBarCode(batchEntity.getBarCode());
                    inventoryEntity.setGoodsUnit(batchEntity.getGoodsUnitId());
                    inventoryEntity.setGoodsBatchNumber(batchEntity.getGoodsBatchNumber());
                    inventoryEntity.setDateInProduced(batchEntity.getDateInProduced());
                    inventoryEntity.setSkuNum(batchEntity.getGoodsQuantity());
                    arrayList.add(inventoryEntity);
                }
            } else {
                AddInventoryEntity inventoryEntity = new AddInventoryEntity();
                inventoryEntity.setGoodsName(entity.getGoodsName());
                inventoryEntity.setGoodsSpec(ListUtil.isListEmpty(entity.getParameter()) ? "" : JSON.toJSONString(entity.getParameter()));
                RepoGoodsEntity goodsEntity = entity.getGoodsBatch().get(0);
                inventoryEntity.setGoodsName(goodsEntity.getName());
                inventoryEntity.setGoodsId(goodsEntity.getId());
                inventoryEntity.setGoodsCode(goodsEntity.getGoodsCode());
                inventoryEntity.setBarCode(goodsEntity.getBarCode());
                inventoryEntity.setGoodsUnit(goodsEntity.getGoodsUnitId());
                inventoryEntity.setGoodsBatchNumber(goodsEntity.getGoodsBatchNumber());
                inventoryEntity.setDateInProduced(goodsEntity.getDateInProduced());
                inventoryEntity.setSkuNum(goodsEntity.getGoodsQuantity());

                arrayList.add(inventoryEntity);
            }
        }
        return JSON.toJSONString(arrayList);
    }

    private String getRepoType(String text) {
        if ("日盘".equals(text)) {
            return "0";
        } else if ("周盘".equals(text)) {
            return "1";
        } else {
            return "2";
        }
    }

    private void initSelectRepoDialog() {
        mSelectRepoDialog = new PosDialog.PosBuilder(mContext, PosDialog.DIALOG_BLACK_TITLE)
                .setRealDialogContent(R.layout.dialog_select_repotory)
                .setUseRadiusBg(false)
                .setDialogTitle("选择仓库")
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .fromRight(true)
                .create();
        RecyclerView rvRepository = mSelectRepoDialog.getView(R.id.rv_repository);
        rvRepository.setLayoutManager(new LinearLayoutManager(mContext));
        mRepoAdapter = new ADA_SelectRepository(mContext);
        mRepoAdapter.setOnItemClickedListener(new ADA_SelectRepository.OnItemClickedListener() {
            @Override
            public void onItemClicked(int position) {

                mSelectedRepo = mRepoAdapter.getDataList().get(position);
                tvRepository.setText(mSelectedRepo.getRepositoryName());
                closeDialog(mSelectRepoDialog);

                // 重新选择仓库后要清空原数据
                mStockCartAdapter.clear();
            }
        });
        rvRepository.setAdapter(mRepoAdapter);
        rvRepository.setHasFixedSize(true);
    }

    private void initScanGoodsDialog() {
        mScanGoodsDialog = new PosDialog.PosBuilder(mContext, PosDialog.DIALOG_BLACK_TITLE)
                .setRealDialogContent(R.layout.dialog_scan_stock_check)
                .setUseRadiusBg(false)
                .setDialogTitle("扫码查询商品")
                .setWidthAndHeight(522, WindowManager.LayoutParams.MATCH_PARENT)
                .fromRight(true)
                .create();
        final EditText etCode = mScanGoodsDialog.getView(R.id.et_code);
        etCode.setInputType(InputType.TYPE_NULL);
        etCode.requestFocus();
        EditTextUtil.hideSoftInputMethod(mContext, etCode);
        etCode.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                String code = v.getText().toString().trim();
                if (actionId == KeyEvent.ACTION_DOWN && !TextUtils.isEmpty(code)) {

                    if (mSelectedRepo == null || TextUtils.isEmpty(mSelectedRepo.getId())) {
                        PosToast.INSTANCE.makeShortToast(mContext, "请先选择仓库");
                        isScanExecuted = false;
                        return true;
                    }

                    if (!NetUtil.isNetworkAvailable(mContext)) {
                        PosToast.INSTANCE.makeShortToast(mContext, "网络不给力，请稍候再试");
                        return true;
                    }

                    if (!isScanExecuted) {
                        mPresenter.loadRepoGoodsById(mSelectedRepo != null ? StringUtils.get(mSelectedRepo.getId()) : "", code, "4");
                        rvCart.setNoMore(false);
                    }
                    isScanExecuted = true;
                    v.setText("");
                }
                return true;
            }
        });
        RecyclerView rvGoodsList = mScanGoodsDialog.getView(R.id.rv_goods_list);
        rvGoodsList.setLayoutManager(new LinearLayoutManager(mContext));
        mScanGoodsAdapter = new ADA_StockCheck(mContext, false);
        mScanGoodsAdapter.setOnItemUncheckedListener(new ADA_StockCheck.OnItemUncheckedListener() {
            @Override
            public void onItemUnchecked() {

                // 如果全部选择后勾选全选按钮，取消某一个时取消选择全选
                for (RepoListGoodsEntity entity : mScanGoodsAdapter.getDataList()) {
                    if (!entity.isChecked()) {
                        cbCheckAll.setChecked(false);
                        return;
                    }
                }
                cbCheckAll.setChecked(true);
            }
        });
        mScanGoodsDialog.getView(R.id.tv_add_stock).setEnabled(true);
        rvGoodsList.setAdapter(mScanGoodsAdapter);
        mScanGoodsDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                etCode.clearFocus();
                etScan.requestFocus();
            }
        });
        cbCheckAll = mScanGoodsDialog.getView(R.id.cb_check_all);
        cbCheckAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mScanGoodsAdapter.updateCheckAllStatus(cbCheckAll.isChecked());
            }
        });
        mScanGoodsDialog.getView(R.id.tv_add_stock).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ListUtil.isListEmpty(mScanGoodsAdapter.getSelectedItems())) {
                    PosToast.INSTANCE.makeShortToast(mContext, "请先选择商品！");
                    return;
                }
                RxBus.getDefault().post(new StockSearchResultEvent(mScanGoodsAdapter.getDataList()));
                closeDialog(mScanGoodsDialog);
            }
        });
    }

    @Override
    public void showRepositoryList(List<RepositoryEntity> repositoryList) {
        if (!ListUtil.isListEmpty(repositoryList)) {
            mSelectRepoDialog.toggleShowEmpty(false, R.id.rv_repository);
            mSelectedRepo = repositoryList.get(0);
            tvRepository.setText(repositoryList.get(0).getRepositoryName());
            mRepoAdapter.update(repositoryList, true);
        } else {
            mSelectRepoDialog.toggleShowEmpty(true, R.id.rv_repository, R.mipmap.ic_bill_empty, "暂未创建仓库");
        }
        llRepository.setClickable(!ListUtil.isListEmpty(repositoryList));
//        tvAddStock.setClickable(!ListUtil.isListEmpty(repositoryList));
    }

    @Override
    public void showScanGoodsDialog(List<RepoListGoodsEntity> list) {
        isScanExecuted = false;
        // 扫码数据
        if (mSelectedRepo == null) {
            showError("请先选择仓库");
            return;
        }

        if (ListUtil.isListEmpty(list)) {
            showError("仓库中无该商品");
            return;
        }

        if (list.size() == 1) {
            ArrayList<RepoListGoodsEntity> scanGoods = new ArrayList<>();
            list.get(0).setChecked(true);
            scanGoods.addAll(list);
            updateLocalList(scanGoods);
            return;
        }
        for (RepoListGoodsEntity entity : list) {
            entity.setChecked(checkGoodsInLocal(entity));
        }
        mScanGoodsAdapter.update(list, true);
        EditText etCode = mScanGoodsDialog.getView(R.id.et_code);
        etScan.clearFocus();
        etCode.requestFocus();
        cbCheckAll.setChecked(false);
        showDialog(mScanGoodsDialog);
    }

    @Override
    public void onGoodSelected(List<RepoListGoodsEntity> list) {

//        addGoodsToLocal(list);

        updateLocalList(list);
    }

    private void updateLocalList(List<RepoListGoodsEntity> searchList) {
        ArrayList<RepoListGoodsEntity> arrayList = new ArrayList<>();

        // 在原列表，但不在搜索列表的数据，需要加入集合
        for (RepoListGoodsEntity localBean : mStockCartAdapter.getDataList()) {
            if (!isLocalBeanInSearchList(searchList, localBean)) {
                arrayList.add(localBean);
            }
        }

        // 把最新的选中数据添加到集合
        for (RepoListGoodsEntity goodsEntity : searchList) {
            if (goodsEntity.isChecked()) {
                arrayList.add(goodsEntity);
            }
        }

        mStockCartAdapter.update(arrayList, true);

        updateStockSearchResultUI(ListUtil.isListEmpty(mStockCartAdapter.getDataList()));
        mGoodsViewAdapter.notifyDataSetChanged();

        tvClear.setEnabled(!ListUtil.isListEmpty(mStockCartAdapter.getDataList()));
        btnGenerate.setEnabled(!ListUtil.isListEmpty(mStockCartAdapter.getDataList()));

    }

    private boolean isLocalBeanInSearchList(List<RepoListGoodsEntity> searchList, RepoListGoodsEntity localBean) {
        for (RepoListGoodsEntity searchBean : searchList) {
            if (localBean.getGoodsId().equals(searchBean.getGoodsId())) {
                return true;
            }
        }
        return false;
    }


    private void addGoodsToLocal(List<RepoListGoodsEntity> list) {
        List<RepoListGoodsEntity> arrayList = new ArrayList<>();
        boolean hasNewData = false;
        for (RepoListGoodsEntity goodsEntity : list) {
            if (!checkGoodsInLocal(goodsEntity)) {
                hasNewData = true;
                arrayList.add(goodsEntity);
            }
        }
        if (!hasNewData) {
            return;
        }
        arrayList.addAll(mStockCartAdapter.getDataList());
        mStockCartAdapter.update(arrayList, true);

        updateStockSearchResultUI(ListUtil.isListEmpty(mStockCartAdapter.getDataList()));
        mGoodsViewAdapter.notifyDataSetChanged();

        tvClear.setEnabled(!ListUtil.isListEmpty(mStockCartAdapter.getDataList()));
        btnGenerate.setEnabled(!ListUtil.isListEmpty(mStockCartAdapter.getDataList()));
    }

    private boolean checkGoodsInLocal(RepoListGoodsEntity goodsEntity) {
        for (RepoListGoodsEntity localEntity : mStockCartAdapter.getDataList()) {
            if (localEntity.getGoodsId().equals(goodsEntity.getGoodsId())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onCheckBillGenerated() {
        btnGenerate.stopLoading("生成盘点单");
        PosToast.INSTANCE.makeCheckMarkToast(mContext, "已生成");
        RxBus.getDefault().post(new MoreViewChangeEvent(MoreViewChangeEvent.MORE_VIE_HOME));
    }

    @Override
    public void onBackPressed(int type) {
        if (type == MoreViewChangeEvent.MORE_VIE_HOME)
            clearStockCheckData();
    }

    private void clearStockCheckData() {

        mStockCartAdapter.clear();
        mScanGoodsAdapter.clear();
        mGoodsViewAdapter = new LRecyclerViewAdapter(mStockCartAdapter);
        rvCart.setAdapter(mGoodsViewAdapter);

        tvClear.setEnabled(false);
        btnGenerate.setEnable(false);

        updateStockSearchResultUI(true);

        rgType.check(R.id.rb_daily);

    }


    @Override
    public void showError(String msg) {
        isScanExecuted = false;
        etScan.requestFocus();
        super.showError(msg);
        btnGenerate.stopLoading("生成盘点单");
    }
}
